import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

/**
 * @author Remi Destigny
 *
 * Server class handle POST/GET request sent to the server 
 * This class does not contains proper error management code as it is only used on a local interface and 
 * thus is unlikely to bring troubles
 */
public final class Server {

	public final static String _SERVER_URL = "http://localhost:50000/lokarria";
	
	/**
	 * Send a POSTrequest to the server
	 * @param path the target url of the POST request
	 * @param data the data of the POST request
	 * @return The server response code or -1 if a problem occured
	 */
	public static int sendPostRequest(String path, String data) {
		URL url;
		try {
			url = new URL(_SERVER_URL + path);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();

			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/json");
			connection.setUseCaches (false);

			OutputStreamWriter out = new OutputStreamWriter(
					connection.getOutputStream());

			out.write(data);
			out.close();

			int rc = connection.getResponseCode();
			
			return rc;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return -1;
	}

	/**
	 * Send a GET request to the server
	 * @param path The target URL of the GET request
	 * @return The server answer or null if an error occured. 
	 */
	public static String sendGetRequest(String path) {

		try {
			URL url = new URL(_SERVER_URL + path);

			URLConnection connection = url.openConnection();

			BufferedReader in = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			Scanner scanner = new Scanner(in);
			String response = scanner.next();
			in.close();
			return response;
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

}
